<template>
  <div class="prescription-detail-page">
    <van-nav-bar
      title="开单详情"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <!-- 选择就诊人区域 -->
    <div class="patient-selector">
      <span class="patient-info">{{ prescription.userName || '王小明' }}</span>
      <div class="switch-btn" @click="switchPatient">
        <van-icon name="contact" size="16px" color="#666" />
        <span>切换</span>
      </div>
    </div>

    <div class="content" v-if="!loading && prescription.id">
      <!-- 支付状态卡片 -->
      <div class="status-card">
        <van-icon name="checked" color="#07c160" size="50px" />
        <div class="status-title">已支付</div>
        <div class="status-message">
          您已缴费成功，如需打印发票请联系医院工作人员，目前药品暂不支持快递配送，请到院门诊药房6号便民窗口取药
        </div>
      </div>

      <!-- 开单信息 -->
      <div class="section">
        <div class="section-title">开单信息</div>
        <div class="info-card">
          <div class="info-row">
            <span class="info-label">申请医院</span>
            <span class="info-value">{{ prescription.hospitalName || '四川省保健院北苑' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">就诊患者</span>
            <span class="info-value">{{ prescription.userName || '王小明' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">登记卡号</span>
            <span class="info-value">{{ prescription.registrationNumber || '2015000010' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">开单金额</span>
            <span class="info-value price">¥{{ formatPrice(prescription.totalAmount) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请时间</span>
            <span class="info-value">{{ formatDateTime(prescription.applicationTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 开单项目 -->
      <div class="section">
        <div class="section-title">开单项目</div>
        
        <!-- 药品项目 -->
        <div 
          v-for="item in drugItems" 
          :key="`drug-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type drug">药</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ formatPrice(item.amount) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}{{ getItemUnit(item.itemType) }}</span>
            <div class="item-tags">
              <span class="item-category">{{ getItemCategory(item.itemName) }}</span>
              <span class="item-tag" v-if="isLimitedDrug(item.itemName)">限购5剂</span>
            </div>
          </div>
        </div>

        <!-- 检查项目 -->
        <div 
          v-for="item in checkupItems" 
          :key="`checkup-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type checkup">查</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ formatPrice(item.amount) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}{{ getItemUnit(item.itemType) }}</span>
          </div>
        </div>

        <!-- 检验项目 -->
        <div 
          v-for="item in testItems" 
          :key="`test-${item.id}`"
          class="item-card"
        >
          <div class="item-header">
            <span class="item-type test">验</span>
            <span class="item-name">{{ item.itemName }}</span>
            <span class="item-price">¥{{ formatPrice(item.amount) }}</span>
          </div>
          <div class="item-details">
            <span>数量：{{ item.quantity }}{{ getItemUnit(item.itemType) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading-spinner" />
    
    <!-- 错误状态 -->
    <div v-if="!loading && !prescription.id" class="error-state">
      <van-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';
import { showNotify } from 'vant';

// 定义药品接口
interface Drug {
  id: number;
  categoryId: number;
  categoryName: string;
  drugName: string;
  dosage: string;
  efficacy: string;
  price: number;
  isPrescription: boolean;
  limitQuantity: number;
  imageUrl: string;
}

// 定义检查项目接口
interface CheckupItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
  notes: string;
}

// 定义检验项目接口
interface TestItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
  notes: string;
}

// 定义购物车项目接口
interface CartItem {
  drug?: Drug;
  checkupItem?: CheckupItem;
  testItem?: TestItem;
  quantity: number;
}

// 接口定义
interface PrescriptionDetail {
  id: number;
  applicationId: number;
  itemType: number;
  itemTypeName: string;
  itemId: number;
  itemName: string;
  quantity: number;
  unitPrice: number;
  amount: number;
}

interface Prescription {
  id: number;
  hospitalId: number;
  hospitalName: string;
  userId: number;
  userName: string;
  applicationTime: string;
  status: number;
  statusName: string;
  totalAmount: number;
  applyReason: string;
  auditorId: number;
  auditorName: string;
  auditTime: string;
  rejectReason: string;
  paymentTime: string;
  cancelTime: string;
  details: PrescriptionDetail[];
  registrationNumber?: string;
}

const route = useRoute();
const router = useRouter();

// 响应式数据
const loading = ref(false);
const prescription = ref<Prescription>({} as Prescription);

// 计算属性 - 药品项目
const drugItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 1) || []
);

// 计算属性 - 检查项目
const checkupItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 2) || []
);

// 计算属性 - 检验项目
const testItems = computed(() => 
  prescription.value.details?.filter(item => item.itemType === 3) || []
);

// 获取项目单位
const getItemUnit = (itemType: number) => {
  switch (itemType) {
    case 1: return '剂';
    case 2: return '次';
    case 3: return '次';
    default: return '';
  }
};

// 获取项目分类
const getItemCategory = (itemName: string) => {
  if (itemName.includes('预防') || itemName.includes('中药')) {
    return '处方5剂';
  }
  return '处方药';
};

// 判断是否限购
const isLimitedDrug = (itemName: string) => {
  return itemName.includes('新冠预防中药');
};

// 格式化价格
const formatPrice = (price: number | undefined) => {
  if (price === undefined || price === null) return '0.00';
  return Number(price).toFixed(2);
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 切换患者
const switchPatient = () => {
  // 返回到处方记录页面进行患者切换
  router.push('/prescription-record');
};

// 根据申请ID获取处方详情
const fetchPrescriptionDetail = async (applicationId: number) => {
  loading.value = true;
  try {
    console.log('发起API请求, URL:', `/Prescription/GetPrescriptionApplicationDetail/${applicationId}`);
    const response = await axiosrnewmedical.get(`/Prescription/GetPrescriptionApplicationDetail/${applicationId}`);
    
    if (response.data.code === 200 && response.data.data) {
      // 转换API返回的数据结构为组件期望的格式
      const apiData = response.data.data;
      prescription.value = {
        id: apiData.id,
        hospitalId: 1,
        hospitalName: apiData.prescriptionInfo.hospitalName,
        userId: 1,
        userName: apiData.prescriptionInfo.patientName,
        applicationTime: apiData.prescriptionInfo.applicationTime,
        status: apiData.prescriptionInfo.status === '已支付' ? 3 : 1,
        statusName: apiData.prescriptionInfo.status,
        totalAmount: apiData.prescriptionInfo.totalAmount,
        applyReason: '',
        auditorId: 1,
        auditorName: '审核员',
        auditTime: '',
        rejectReason: '',
        paymentTime: apiData.prescriptionInfo.applicationTime,
        cancelTime: '',
        registrationNumber: apiData.prescriptionInfo.cardNo,
        details: apiData.items.map((item: { id: number; itemName: string; quantityText: string; amount: number }) => ({
          id: item.id,
          applicationId: apiData.id,
          itemType: 1, // 假设都是药品
          itemTypeName: '药品',
          itemId: item.id,
          itemName: item.itemName,
          quantity: parseInt(item.quantityText.match(/\d+/)?.[0] || '1'),
          unitPrice: item.amount,
          amount: item.amount
        }))
      };
      console.log('成功获取处方详情:', prescription.value);
      console.log('患者姓名应该是:', apiData.prescriptionInfo.patientName);
    } else {
      console.error('获取处方详情失败:', response.data.msg);
      // 使用示例数据作为降级方案
      loadSampleData(applicationId);
    }
  } catch (error) {
    console.error('获取处方详情异常:', error);
    console.log('异常详细信息:', error);
    // 使用示例数据作为降级方案
    loadSampleData(applicationId);
  } finally {
    loading.value = false;
  }
};

// 加载示例数据
const loadSampleData = (applicationId: number) => {
  console.log('API调用失败，使用示例数据, applicationId:', applicationId);
  
  // 根据applicationId匹配对应的示例数据
  const sampleDataMap: { [key: number]: Prescription } = {
    27: {
      id: 27,
      hospitalId: 1,
      hospitalName: '上海浦东医院',
      userId: 1,
      userName: '王小珂',
      applicationTime: '2025-08-06 19:36:54',
      status: 3,
      statusName: '已支付',
      totalAmount: 19.16,
      applyReason: '',
      auditorId: 1,
      auditorName: '审核员',
      auditTime: '2025-08-06 20:00:00',
      rejectReason: '',
      paymentTime: '2025-08-06 20:30:00',
      cancelTime: '',
      registrationNumber: '110101********4171',
      details: [
        {
          id: 1,
          applicationId: 27,
          itemType: 1,
          itemTypeName: '药品',
          itemId: 1,
          itemName: '新冠预防中药（儿童人群）',
          quantity: 1,
          unitPrice: 19.16,
          amount: 19.16
        }
      ]
    },
    28: {
      id: 28,
      hospitalId: 1,
      hospitalName: '上海浦东医院',
      userId: 1,
      userName: '王小珂',
      applicationTime: '2025-08-06 19:27:00',
      status: 3,
      statusName: '已支付',
      totalAmount: 10.08,
      applyReason: '',
      auditorId: 1,
      auditorName: '审核员',
      auditTime: '2025-08-06 19:30:00',
      rejectReason: '',
      paymentTime: '2025-08-06 19:45:00',
      cancelTime: '',
      registrationNumber: '110101********4171',
      details: [
        {
          id: 1,
          applicationId: 28,
          itemType: 1,
          itemTypeName: '药品',
          itemId: 2,
          itemName: '新冠预防中药（正常人群）',
          quantity: 1,
          unitPrice: 10.08,
          amount: 10.08
        }
      ]
    },
    29: {
      id: 29,
      hospitalId: 1,
      hospitalName: '上海浦东医院',
      userId: 1,
      userName: '王小珂',
      applicationTime: '2025-08-06 18:42:58',
      status: 3,
      statusName: '已支付',
      totalAmount: 9.08,
      applyReason: '',
      auditorId: 1,
      auditorName: '审核员',
      auditTime: '2025-08-06 18:45:00',
      rejectReason: '',
      paymentTime: '2025-08-06 19:00:00',
      cancelTime: '',
      registrationNumber: '110101********4171',
      details: [
        {
          id: 1,
          applicationId: 29,
          itemType: 1,
          itemTypeName: '药品',
          itemId: 3,
          itemName: '新冠预防中药（儿童人群）',
          quantity: 1,
          unitPrice: 9.08,
          amount: 9.08
        }
      ]
    }
  };

  // 获取对应的示例数据，如果不存在则使用默认数据
  prescription.value = sampleDataMap[applicationId] || sampleDataMap[27];
  
  showNotify({ 
    type: 'warning', 
    message: '正在使用示例数据显示处方详情' 
  });
};

// 初始化数据
const initData = () => {
  const applicationId = route.query.id;
  if (applicationId) {
    // 使用API接口获取处方详情
    fetchPrescriptionDetail(Number(applicationId));
  } else {
    // 如果没有传递ID，使用示例数据（兼容旧的路由方式）
    const hospitalName = route.query.hospitalName as string || '四川省保健院北苑';
    const patientName = route.query.patientName as string || '王小明';
    const totalAmount = Number(route.query.totalAmount) || 201.00;
    const cartItemsStr = route.query.cartItems as string;
    
    let cartItems: CartItem[] = [];
    if (cartItemsStr) {
      try {
        cartItems = JSON.parse(decodeURIComponent(cartItemsStr));
      } catch (error) {
        console.error('解析购物车数据失败:', error);
      }
    }

    // 如果没有传递购物车数据，使用示例数据
    if (cartItems.length === 0) {
      // 直接设置示例数据，不依赖购物车结构
      prescription.value = {
        id: 27,
        hospitalId: 1,
        hospitalName: '四川省保健院北苑',
        userId: 1,
        userName: '王小明',
        applicationTime: '2020-01-01 10:30:20',
        status: 2,
        statusName: '已支付',
        totalAmount: 201.00,
        applyReason: '',
        auditorId: 0,
        auditorName: '',
        auditTime: '',
        rejectReason: '',
        paymentTime: '',
        cancelTime: '',
        registrationNumber: '2015000010',
        details: [
          {
            id: 1,
            applicationId: 27,
            itemType: 1,
            itemTypeName: '药品',
            itemId: 1,
            itemName: '新冠预防中药（正常人群）',
            quantity: 1,
            unitPrice: 11.80,
            amount: 11.80
          },
          {
            id: 2,
            applicationId: 27,
            itemType: 1,
            itemTypeName: '药品',
            itemId: 2,
            itemName: '云南白药胶囊 0.5g*20片',
            quantity: 1,
            unitPrice: 10.08,
            amount: 10.08
          },
          {
            id: 3,
            applicationId: 27,
            itemType: 3,
            itemTypeName: '检查',
            itemId: 3,
            itemName: '动态心电图',
            quantity: 1,
            unitPrice: 150.00,
            amount: 150.00
          }
        ]
      };
      return;
    }

    // 处理从购物车传递的数据
    const details: PrescriptionDetail[] = [];
    cartItems.forEach((cartItem, index) => {
      if (cartItem.drug) {
        details.push({
          id: index + 1,
          applicationId: 27,
          itemType: 1,
          itemTypeName: '药品',
          itemId: cartItem.drug.id,
          itemName: cartItem.drug.drugName + (cartItem.drug.dosage ? ` ${cartItem.drug.dosage}` : ''),
          quantity: cartItem.quantity,
          unitPrice: cartItem.drug.price,
          amount: cartItem.drug.price * cartItem.quantity
        });
      } else if (cartItem.checkupItem) {
        details.push({
          id: index + 1,
          applicationId: 27,
          itemType: 2,
          itemTypeName: '检查',
          itemId: cartItem.checkupItem.id,
          itemName: cartItem.checkupItem.itemName,
          quantity: cartItem.quantity,
          unitPrice: cartItem.checkupItem.price,
          amount: cartItem.checkupItem.price * cartItem.quantity
        });
      } else if (cartItem.testItem) {
        details.push({
          id: index + 1,
          applicationId: 27,
          itemType: 3,
          itemTypeName: '检验',
          itemId: cartItem.testItem.id,
          itemName: cartItem.testItem.itemName,
          quantity: cartItem.quantity,
          unitPrice: cartItem.testItem.price,
          amount: cartItem.testItem.price * cartItem.quantity
        });
      }
    });

    prescription.value = {
      id: 27,
      hospitalId: 1,
      hospitalName: hospitalName,
      userId: 1,
      userName: patientName,
      applicationTime: '2020-01-01 10:30:20',
      status: 2,
      statusName: '已支付',
      totalAmount: totalAmount,
      applyReason: '',
      auditorId: 0,
      auditorName: '',
      auditTime: '',
      rejectReason: '',
      paymentTime: '',
      cancelTime: '',
      details,
      registrationNumber: '2015000010'
    };
  }
};

onMounted(() => {
  initData();
});
</script>

<style scoped>
.prescription-detail-page {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #666;
}

.circle-btn {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #666;
}

.patient-selector {
  background-color: #f7f8fa;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebedf0;
}

.patient-info {
  color: #323233;
  font-size: 14px;
  font-weight: 500;
}

.switch-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #969799;
  font-size: 14px;
  cursor: pointer;
}

.switch-btn:active {
  opacity: 0.7;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px 20px;
}

.status-card {
  background: white;
  border-radius: 12px;
  padding: 32px 24px;
  margin: 16px 0;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.status-title {
  font-size: 20px;
  font-weight: 600;
  color: #323233;
  margin: 12px 0;
}

.status-message {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
}

.section {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
  padding: 0 4px;
}

.info-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.info-row:not(:last-child) {
  border-bottom: 1px solid #f5f5f5;
}

.info-label {
  color: #969799;
}

.info-value {
  color: #323233;
  font-weight: 500;
}

.info-value.price {
  color: #ee0a24;
  font-size: 16px;
  font-weight: 600;
}

.item-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.item-type {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  font-weight: 600;
  margin-right: 8px;
  flex-shrink: 0;
}

.item-type.drug {
  background-color: #1890ff;
}

.item-type.checkup {
  background-color: #52c41a;
}

.item-type.test {
  background-color: #fa8c16;
}

.item-name {
  flex: 1;
  font-size: 14px;
  color: #323233;
  margin-right: 8px;
}

.item-price {
  font-size: 16px;
  font-weight: 600;
  color: #ee0a24;
}

.item-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #969799;
}

.item-tags {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.item-category {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  color: #666;
}

.item-tag {
  background-color: #ff976a;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.loading-spinner {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.error-state {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}
</style> 